#include "setloginaccountwindow.h"

#include <QMessageBox>
#include <QString>
#include <fstream>
#include <string>

#include "mysqlapi.h"
#include "transassistanceqstring2string.h"
#include "ui_setloginaccountwindow.h"

SetLoginAccountWindow::SetLoginAccountWindow(QWidget *parent)
    : QDialog(parent),
      ui(new Ui::SetLoginAccountWindow) {
    ui->setupUi(this);

    try {
        std::ifstream fin("../data/account");
        if (!fin.is_open()) throw 1;
        std::string tmp[3];
        if (!std::getline(fin, tmp[0]).good()) throw 2;
        if (!std::getline(fin, tmp[1]).good()) throw 2;
        if (!std::getline(fin, tmp[2]).good()) throw 2;
        ui->host_input->setPlaceholderText(tmp[0].c_str());
        ui->user_input->setPlaceholderText(tmp[1].c_str());
        ui->password_input->setPlaceholderText(tmp[2].c_str());
        fin.close();
    } catch (int) {
    }

    ui->host_input->setText(str2qstr(MysqlAPI::host_));
    ui->user_input->setText(str2qstr(MysqlAPI::user_));
    ui->password_input->setText(str2qstr(MysqlAPI::password_));
}

SetLoginAccountWindow::~SetLoginAccountWindow() {
    // set the default value
    if ("" == MysqlAPI::host_) MysqlAPI::host_ = std::move(qstr2str(ui->host_input->placeholderText()));
    if ("" == MysqlAPI::user_) MysqlAPI::user_ = std::move(qstr2str(ui->user_input->placeholderText()));
    if ("" == MysqlAPI::password_) MysqlAPI::password_ = std::move(qstr2str(ui->password_input->placeholderText()));

    // store the account
    std::ofstream fout("../data/account");
    fout << (MysqlAPI::host_ + "\n");
    fout << (MysqlAPI::user_ + "\n");
    fout << (MysqlAPI::password_ + "\n");
    fout.close();
    delete ui;
}

void SetLoginAccountWindow::on_OK_clicked() {
    MysqlAPI::host_ = std::move(qstr2str(ui->host_input->text()));
    MysqlAPI::user_ = std::move(qstr2str(ui->user_input->text()));
    MysqlAPI::password_ = std::move(qstr2str(ui->password_input->text()));
    close();
}
